import Vue from 'vue'
import store from '@/store'
import DataDict from '@/utils/dict'

import {axiosAuth} from '@/utils/request'

function searchDictByKey(dict, key) {
    if (key == null && key == "") {
        return null
    }
    try {
        for (let i = 0; i < dict.length; i++) {
            if (dict[i].key == key) {
                return dict[i].value
            }
        }
    } catch (e) {
        return null
    }
}

function install() {
    Vue.use(DataDict, {
        metas: {
            '*': {
                labelField: 'dictLabel',
                valueField: 'dictValue',
                request(dictMeta) {
                    let dictMetaList = dictMeta.map(key => {
                        return key.type
                    })

                    return new Promise((resolve, reject) => {
                        axiosAuth({
                            url: '/sysDictData/byDictTypeIn',
                            method: 'post',
                            data: dictMetaList
                        }).then(res => {
                            let data = res.data
                            for (const key in data) {
                                let dict = data[key]
                                store.dispatch('dict/setDict', {key: dict.dictType, value: dict.sysDictDataList})
                            }
                            resolve(res.data)
                        }).catch(error => {
                            reject(error)
                        })
                    })
                    // const storeDict = searchDictByKey(store.getters.dict, dictMeta.type)
                    // if (storeDict) {
                    //   return new Promise(resolve => {
                    //     resolve(storeDict)
                    //   })
                    // } else {
                    // }
                },
            },
        },
    })
}

export default {
    install,
}
